"use client"

import { useState } from "react"
import { Plus, Trash2, Users } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Card, CardContent } from "@/components/ui/card"
import { LayoutPreview } from "@/components/layout-preview"
import { LayoutCode } from "@/components/layout-code"
import { ParticipantsList } from "@/components/participants-list"
import { AddParticipantDialog } from "@/components/add-participant-dialog"
import { useToast } from "@/hooks/use-toast"
import { Participant, ParticipantType } from "@/lib/types"
import { v4 as uuidv4 } from "uuid"

// 定义布局元素类型
type LayoutElement = {
  id: string
  x: number
  y: number
  width: number
  height: number
  zIndex: number
  label: string
  participantId?: string
}

// 预设布局模板
const layoutTemplates = {
  "1x1": { rows: 1, cols: 1 },
  "2x2": { rows: 2, cols: 2 },
  "3x3": { rows: 3, cols: 3 },
  "1+5": { custom: true, name: "1大5小" },
  "1+7": { custom: true, name: "1大7小" },
  "2+8": { custom: true, name: "2大8小" },
}

export function LayoutDesigner() {
  const { toast } = useToast()
  const [layoutName, setLayoutName] = useState("新布局")
  const [canvasSize, setCanvasSize] = useState({ width: 1280, height: 720 })
  const [elements, setElements] = useState<LayoutElement[]>([])
  const [selectedElement, setSelectedElement] = useState<string | null>(null)
  const [activeTab, setActiveTab] = useState("design")
  const [participants, setParticipants] = useState<Participant[]>([])
  const [addParticipantDialogOpen, setAddParticipantDialogOpen] = useState(false)
  
  // 添加参与者
  const addParticipant = (name: string, type: ParticipantType) => {
    const newParticipant: Participant = {
      id: uuidv4(),
      name,
      type,
    }
    setParticipants([...participants, newParticipant])
    toast({
      title: "已添加参与者",
      description: `已添加 ${name}`,
    })
  }

  // 删除参与者
  const removeParticipant = (participantId: string) => {
    // 移除参与者的同时，清除相关元素的参与者引用
    setElements(elements.map(element => ({
      ...element,
      participantId: element.participantId === participantId ? undefined : element.participantId
    })))
    setParticipants(participants.filter(p => p.id !== participantId))
    toast({
      title: "已删除参与者",
      description: "参与者已被移除",
    })
  }

  // 分配参与者到元素
  const assignParticipant = (elementId: string, participantId: string) => {
    setElements(elements.map(element => 
      element.id === elementId 
        ? { ...element, participantId }
        : element
    ))
    toast({
      title: "已分配参与者",
      description: "参与者已分配到布局元素",
    })
  }

  // 从元素移除参与者
  const removeParticipantFromElement = (elementId: string) => {
    setElements(elements.map(element =>
      element.id === elementId
        ? { ...element, participantId: undefined }
        : element
    ))
    toast({
      title: "已移除参与者",
      description: "参与者已从布局元素移除",
    })
  }

  // 添加新元素
  const addElement = () => {
    const newElement: LayoutElement = {
      id: `element-${Date.now()}`,
      x: 10,
      y: 10,
      width: 320,
      height: 240,
      zIndex: elements.length,
      label: `参与者 ${elements.length + 1}`,
    }

    setElements([...elements, newElement])
    setSelectedElement(newElement.id)

    toast({
      title: "已添加新元素",
      description: `已添加 ${newElement.label}`,
    })
  }

  // 删除元素
  const removeElement = (id: string) => {
    setElements(elements.filter((el) => el.id !== id))
    if (selectedElement === id) {
      setSelectedElement(null)
    }

    toast({
      title: "已删除元素",
      description: "布局元素已被移除",
    })
  }

  // 更新元素属性
  const updateElement = (id: string, updates: Partial<LayoutElement>) => {
    setElements(elements.map((el) => (el.id === id ? { ...el, ...updates } : el)))
  }

  // 应用模板
  const applyTemplate = (template: string) => {
    const templateConfig = layoutTemplates[template as keyof typeof layoutTemplates]

    if (!templateConfig) return

    let newElements: LayoutElement[] = []

    if ("rows" in templateConfig && "cols" in templateConfig) {
      const { rows, cols } = templateConfig
      const cellWidth = canvasSize.width / cols
      const cellHeight = canvasSize.height / rows

      for (let r = 0; r < rows; r++) {
        for (let c = 0; c < cols; c++) {
          const index = r * cols + c
          newElements.push({
            id: `element-${Date.now()}-${index}`,
            x: c * cellWidth,
            y: r * cellHeight,
            width: cellWidth,
            height: cellHeight,
            zIndex: index,
            label: `参与者 ${index + 1}`,
          })
        }
      }
    } else if (template === "1+5") {
      // 1大5小布局
      newElements = [
        // 主讲人（大）
        {
          id: `element-${Date.now()}-0`,
          x: 0,
          y: 0,
          width: canvasSize.width * 0.75,
          height: canvasSize.height,
          zIndex: 0,
          label: "主讲人",
        },
        // 5个小窗口
        ...Array(5)
          .fill(0)
          .map((_, i) => ({
            id: `element-${Date.now()}-${i + 1}`,
            x: canvasSize.width * 0.75,
            y: i * (canvasSize.height / 5),
            width: canvasSize.width * 0.25,
            height: canvasSize.height / 5,
            zIndex: i + 1,
            label: `参与者 ${i + 1}`,
          })),
      ]
    } else if (template === "1+7") {
      // 1大7小布局
      newElements = [
        // 主讲人（大）
        {
          id: `element-${Date.now()}-0`,
          x: canvasSize.width * 0.25,
          y: 0,
          width: canvasSize.width * 0.75,
          height: canvasSize.height * 0.75,
          zIndex: 0,
          label: "主讲人",
        },
        // 左侧3个小窗口
        ...Array(3)
          .fill(0)
          .map((_, i) => ({
            id: `element-${Date.now()}-${i + 1}`,
            x: 0,
            y: i * (canvasSize.height / 3),
            width: canvasSize.width * 0.25,
            height: canvasSize.height / 3,
            zIndex: i + 1,
            label: `参与者 ${i + 1}`,
          })),
        // 底部4个小窗口
        ...Array(4)
          .fill(0)
          .map((_, i) => ({
            id: `element-${Date.now()}-${i + 4}`,
            x: canvasSize.width * 0.25 + i * ((canvasSize.width * 0.75) / 4),
            y: canvasSize.height * 0.75,
            width: (canvasSize.width * 0.75) / 4,
            height: canvasSize.height * 0.25,
            zIndex: i + 4,
            label: `参与者 ${i + 4}`,
          })),
      ]
    } else if (template === "2+8") {
      // 2大8小布局
      newElements = [
        // 2个大窗口
        {
          id: `element-${Date.now()}-0`,
          x: 0,
          y: 0,
          width: canvasSize.width * 0.5,
          height: canvasSize.height * 0.7,
          zIndex: 0,
          label: "主讲人 1",
        },
        {
          id: `element-${Date.now()}-1`,
          x: canvasSize.width * 0.5,
          y: 0,
          width: canvasSize.width * 0.5,
          height: canvasSize.height * 0.7,
          zIndex: 1,
          label: "主讲人 2",
        },
        // 8个小窗口
        ...Array(8)
          .fill(0)
          .map((_, i) => ({
            id: `element-${Date.now()}-${i + 2}`,
            x: i * (canvasSize.width / 8),
            y: canvasSize.height * 0.7,
            width: canvasSize.width / 8,
            height: canvasSize.height * 0.3,
            zIndex: i + 2,
            label: `参与者 ${i + 1}`,
          })),
      ]
    }

    setElements(newElements)
    toast({
      title: "已应用模板",
      description: `已应用 ${template} 模板`,
    })
  }

  // 生成FreeSWITCH XML配置
  const generateXmlConfig = () => {
    let xml = `<configuration name="conference_layouts.conf" description="Conference Layout">
  <layouts>
    <layout name="${layoutName}">
`

    elements.forEach((el, index) => {
      const x = Math.round((el.x / canvasSize.width) * 100) / 100
      const y = Math.round((el.y / canvasSize.height) * 100) / 100
      const width = Math.round((el.width / canvasSize.width) * 100) / 100
      const height = Math.round((el.height / canvasSize.height) * 100) / 100

      xml += `      <image x="${x}" y="${y}" scale="${width}x${height}" floor="${index}" overlap="true" reservation_id="${index + 1}" zoom="${index === 0 ? "0" : "0"}"/>\n`
    })

    xml += `    </layout>
  </layouts>
</configuration>`

    return xml
  }

  return (
    <>
      <AddParticipantDialog
        open={addParticipantDialogOpen}
        onOpenChange={setAddParticipantDialogOpen}
        onSubmit={addParticipant}
      />
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <div className="lg:col-span-2">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="design">设计视图</TabsTrigger>
            <TabsTrigger value="code">代码视图</TabsTrigger>
          </TabsList>
          <TabsContent value="design" className="mt-4">
            <Card>
              <CardContent className="p-4">
                <LayoutPreview
                  elements={elements}
                  canvasSize={canvasSize}
                  selectedElement={selectedElement}
                  setSelectedElement={setSelectedElement}
                  updateElement={updateElement}
                  participants={participants}
                  assignParticipant={assignParticipant}
                  removeParticipant={removeParticipantFromElement}
                />
              </CardContent>
            </Card>
          </TabsContent>
          <TabsContent value="code" className="mt-4">
            <Card>
              <CardContent className="p-4">
                <LayoutCode xml={generateXmlConfig()} />
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>

      <div className="space-y-6">
        <Card>
          <CardContent className="p-4 space-y-4">
            <h3 className="text-lg font-medium">布局设置</h3>

            <div className="space-y-2">
              <Label htmlFor="layout-name">布局名称</Label>
              <Input id="layout-name" value={layoutName} onChange={(e) => setLayoutName(e.target.value)} />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="canvas-width">画布宽度</Label>
                <Input
                  id="canvas-width"
                  type="number"
                  value={canvasSize.width}
                  onChange={(e) => setCanvasSize({ ...canvasSize, width: Number.parseInt(e.target.value) || 1280 })}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="canvas-height">画布高度</Label>
                <Input
                  id="canvas-height"
                  type="number"
                  value={canvasSize.height}
                  onChange={(e) => setCanvasSize({ ...canvasSize, height: Number.parseInt(e.target.value) || 720 })}
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label>应用模板</Label>
              <div className="grid grid-cols-3 gap-2">
                {Object.entries(layoutTemplates).map(([key, value]) => (
                  <Button key={key} variant="outline" onClick={() => applyTemplate(key)}>
                    {"custom" in value ? value.name : `${key}`}
                  </Button>
                ))}
              </div>
            </div>

            <Button onClick={addElement} className="w-full">
              <Plus className="mr-2 h-4 w-4" /> 添加元素
            </Button>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4 space-y-4">
            <h3 className="text-lg font-medium">参与者管理</h3>
            
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <Label>参与者列表</Label>
                <Button 
                  size="sm" 
                  onClick={() => setAddParticipantDialogOpen(true)}
                >
                  <Plus className="mr-2 h-4 w-4" /> 添加参与者
                </Button>
              </div>
              
              <div className="text-sm text-gray-500 mb-2">
                将参与者拖放到布局元素上进行分配
              </div>
              
              <ParticipantsList 
                participants={participants}
                removeParticipant={removeParticipant}
              />
            </div>
          </CardContent>
        </Card>

        {selectedElement && (
          <Card>
            <CardContent className="p-4 space-y-4">
              <h3 className="text-lg font-medium">元素属性</h3>

              {elements.find((el) => el.id === selectedElement) && (
                <>
                  <div className="space-y-2">
                    <Label htmlFor="element-label">标签</Label>
                    <Input
                      id="element-label"
                      value={elements.find((el) => el.id === selectedElement)?.label || ""}
                      onChange={(e) => updateElement(selectedElement, { label: e.target.value })}
                    />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="element-x">X 坐标</Label>
                      <Input
                        id="element-x"
                        type="number"
                        value={elements.find((el) => el.id === selectedElement)?.x || 0}
                        onChange={(e) => updateElement(selectedElement, { x: Number.parseInt(e.target.value) || 0 })}
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="element-y">Y 坐标</Label>
                      <Input
                        id="element-y"
                        type="number"
                        value={elements.find((el) => el.id === selectedElement)?.y || 0}
                        onChange={(e) => updateElement(selectedElement, { y: Number.parseInt(e.target.value) || 0 })}
                      />
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="element-width">宽度</Label>
                      <Input
                        id="element-width"
                        type="number"
                        value={elements.find((el) => el.id === selectedElement)?.width || 0}
                        onChange={(e) =>
                          updateElement(selectedElement, { width: Number.parseInt(e.target.value) || 0 })
                        }
                      />
                    </div>
                    <div className="space-y-2">
                      <Label htmlFor="element-height">高度</Label>
                      <Input
                        id="element-height"
                        type="number"
                        value={elements.find((el) => el.id === selectedElement)?.height || 0}
                        onChange={(e) =>
                          updateElement(selectedElement, { height: Number.parseInt(e.target.value) || 0 })
                        }
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="element-zindex">层级 (Z-Index)</Label>
                    <Input
                      id="element-zindex"
                      type="number"
                      value={elements.find((el) => el.id === selectedElement)?.zIndex || 0}
                      onChange={(e) => updateElement(selectedElement, { zIndex: Number.parseInt(e.target.value) || 0 })}
                    />
                  </div>

                  <Button variant="destructive" onClick={() => removeElement(selectedElement)} className="w-full">
                    <Trash2 className="mr-2 h-4 w-4" /> 删除元素
                  </Button>
                </>
              )}
            </CardContent>
          </Card>
        )}
      </div>
      </div>
    </>
  )
}